package com.gjy.util.sb.advice;

import com.gjy.util.sb.entity.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.time.LocalDate;
import java.util.Objects;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-23 17:11:28
 */
@RestControllerAdvice
@Order(100)
public class ResponseBodyAdviceImpl implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(ResponseBodyAdviceImpl.class);

    @Override
    public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> cls) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object result, MethodParameter parameter, MediaType type, Class<? extends HttpMessageConverter<?>> cls, ServerHttpRequest request, ServerHttpResponse response) {
        // 可以从 redis 中查看数据, 判断某个值是不是存在, 然后判断是否操作 redisson
        // RMap<String, String> map = redissonClient.getMap(Constants.MES_DOCUMENT_LOCK_REMIND_PREFIX_ + Thread.currentThread().getId());
        if (result instanceof AjaxResult) {
            AjaxResult ar = (AjaxResult) result;
            if (Objects.requireNonNull(ar).getCode() == 600) {
                AjaxResult r = new AjaxResult();
                r.setCode(200);
                r.setMessage("此数据已存在");
                r.setData(LocalDate.now());
                log.info("impl: {}", r);
                return r;
            }
        } else {
            log.info("r:{}", result);
        }
        return result;
    }

}
